package com.schoolgard.action.device;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;

import com.schoolegard.services.DeviceService;
import com.schoolegard.services.HdTypeService;
import com.schoolegard.services.LocationService;
import com.schoolegard.services.OrganizationService;
import com.schoolegard.services.ParamsService;
import com.schoolegard.services.RegionsService;
import com.schoolegard.services.TerminalService;
import com.schoolgard.base.BaseAction;
import com.schoolgard.entitybean.Device;
import com.schoolgard.entitybean.GridDataModel;
import com.schoolgard.entitybean.HdType;
import com.schoolgard.entitybean.Location;
import com.schoolgard.entitybean.Organization;
import com.schoolgard.entitybean.Params;
import com.schoolgard.entitybean.Regions;
import com.schoolgard.entitybean.SchoolData;
import com.schoolgard.entitybean.Terminal;
import com.schoolgard.entitybean.TreeDataModel;
import com.supersystem.utils.JSONUtils;
import com.supersystem.utils.RandomGUID;

public class ReOrDeTeAction extends BaseAction{
	
	private RegionsService regionsService;
	private OrganizationService organizationService;
	private DeviceService deviceService;
	private TerminalService terminalService;
	private HdTypeService hdTypeService;
	private ParamsService paramsService;
	private LocationService locationService; 
	
	private Regions re;
	private Organization orgni;
	private Device de;
	private Terminal te;
	
	/**
	 * 查找所有数据，包括区域、组织、设备、终端
	 * 使用懒加载策略，如果传递过来的id为区域，
	 * 则查询是否还有下一级区域或者本级区域是否有
	 * 组织，然后将数据返回，不检测返回节点是否
	 * 有子节点，不到终端始终显示成有子节点状态
	 */
	public void queryAll()
	{
		/**
		 * 传递过来的id要包含标识符号，比如区域有re_、组织有or_、设备有de_、终端有te_
		 */
		 String queryId = request.getParameter("queryId");
		 writeToResponse(JSONUtils.toJSONString(queryByParent(queryId,true)));
	}
	
	public void queryForDevice(){
		String queryId = request.getParameter("queryId");
		 writeToResponse(JSONUtils.toJSONString(queryByParent(queryId,false)));
	}
	
	/**
	 * 查询设备节点
	 * @param queryId
	 * @param isRemark 是否备注【区域】等
	 * @return
	 */
	public List<TreeDataModel> queryByParent(String queryId,boolean isRemark){
		List<TreeDataModel> treeNodes = new ArrayList<TreeDataModel>();
		Location loc = null;
		if(StringUtils.isBlank(queryId) || "null".equals(queryId)){ //为空则查询第一层区域数据
			List<Regions> regions_lev_1s = regionsService.findLevelOne();
			for (Regions regions : regions_lev_1s) {
				TreeDataModel regionsTree = new TreeDataModel();
			    loc = locationService.findByRefId(regions.getId().toString());
			    if(loc != null)
				regionsTree.setUserData(loc.getXAxis()+","+loc.getYAxis());
				regionsTree.setId("re_"+regions.getId());
				if(isRemark){
					regionsTree.setText(regions.getName()+"<span style=\"color:blue\">【区域】</span>");
				}else{
					regionsTree.setText(regions.getName());
				}
				regionsTree.setHasChildren(true);
				treeNodes.add(regionsTree);
			}
		    return 	treeNodes;
		}else{ //按照id类型处理
			if(queryId.indexOf("re_")!=-1){//查询子区域和本区域下面的第一层组织
				Long regionsId = Long.valueOf(queryId.replace("re_", "").trim());
				List<Regions> children_regions = regionsService.findListByParentId(regionsId);
				List<Organization> children_orgs = organizationService.find_level_1_ByRegions(regionsId); //查找区域的直接子节点
				for(int i=0 ; i<children_regions.size() ; i++){
					Regions reg = children_regions.get(i);
					TreeDataModel regionsTree = new TreeDataModel();
					loc = locationService.findByRefId(reg.getId().toString());
					if(loc != null)
					regionsTree.setUserData(loc.getXAxis()+","+loc.getYAxis());
					regionsTree.setHasChildren(true);
					regionsTree.setId("re_"+reg.getId());
					if(isRemark){
						regionsTree.setText(reg.getName()+"<span style=\"color:blue\">【区域】</span>");
					}else{
						regionsTree.setText(reg.getName());
					}
					List<TreeDataModel> children = queryByParent("re_"+reg.getId(),isRemark);
					regionsTree.setChildren(children);
					treeNodes.add(regionsTree);
				}
				for(int j=0 ; j<children_orgs.size() ; j++){
					Organization org = children_orgs.get(j);
					TreeDataModel organizationTree = new TreeDataModel();
					loc = locationService.findByRefId(org.getId().toString());
					if(loc != null)
					organizationTree.setUserData(loc.getXAxis()+","+loc.getYAxis());
					organizationTree.setHasChildren(true);
					organizationTree.setId("or_"+org.getId());
					if(isRemark){
						organizationTree.setText(org.getName()+"<span style=\"color:blue\">【组织】</span>");
					}else{
						organizationTree.setText(org.getName());
					}
					treeNodes.add(organizationTree);
				}
				
			}else if(queryId.indexOf("or_")!=-1){ //查询子组织和组织下面的设备
				Long orgId = Long.valueOf(queryId.replace("or_", "").trim());
				List<Organization> children_organizations = organizationService.findByParentId(orgId);
				List<Device> children_devices = deviceService.findByOrganization(orgId); //查找组织的直接子节点
				for(int i=0 ; i<children_organizations.size() ; i++){
					Organization org = children_organizations.get(i);
					TreeDataModel organizationsTree = new TreeDataModel();
					loc = locationService.findByRefId(org.getId().toString());
					if(loc != null)
					organizationsTree.setUserData(loc.getXAxis()+","+loc.getYAxis());
					organizationsTree.setHasChildren(true);
					organizationsTree.setId("or_"+org.getId());
					if(isRemark){
						organizationsTree.setText(org.getName()+"<span style=\"color:blue\">【组织】</span>");
					}else{
						organizationsTree.setText(org.getName());
					}
					List<TreeDataModel> children = queryByParent("or_"+org.getId(),isRemark);
					organizationsTree.setChildren(children);
					treeNodes.add(organizationsTree);
				}
				for(int j=0 ; j<children_devices.size() ; j++){
					Device device = children_devices.get(j);
					TreeDataModel deviceTree = new TreeDataModel();
					loc = locationService.findByRefId(device.getGuid());
					if(loc != null)
					deviceTree.setUserData(loc.getXAxis()+","+loc.getYAxis());
					deviceTree.setHasChildren(true);
					deviceTree.setId("de_"+device.getGuid());
					if(isRemark){
						deviceTree.setText(device.getName()+"<span style=\"color:blue\">【设备】</span>");
					}else{
						deviceTree.setText(device.getName());
					}
					treeNodes.add(deviceTree);
				}
			}else if(queryId.indexOf("de_")!=-1){ //查找所有设备对应的终端
				String deviceId = queryId.replace("de_", "").trim();
				List<Device> children_device = deviceService.findByParentId(deviceId);
				List<Terminal> terminals = terminalService.findByDevice(deviceId); //查找设备的子节点
				
				for(int i=0 ; i<children_device.size() ; i++){
					Device device = children_device.get(i);
					TreeDataModel deviceTree = new TreeDataModel();
					loc = locationService.findByRefId(device.getGuid());
					if(loc != null)
					deviceTree.setUserData(loc.getXAxis()+","+loc.getYAxis());
					deviceTree.setHasChildren(true);
					deviceTree.setId("de_"+device.getGuid());
					if(isRemark){
						deviceTree.setText(device.getName()+"<span style=\"color:blue\">【设备】</span>");
					}else{
						deviceTree.setText(device.getName());
					}
					List<TreeDataModel> children = queryByParent("de_"+device.getGuid(),isRemark);
					deviceTree.setChildren(children);
					treeNodes.add(deviceTree);
				}
				
				for(int i=0 ; i<terminals.size() ; i++){
					Terminal term = terminals.get(i);
					TreeDataModel terTree = new TreeDataModel();
					loc = locationService.findByRefId(term.getGuid());
					if(loc != null)
					terTree.setUserData(loc.getXAxis()+","+loc.getYAxis());
					terTree.setId("te_"+term.getGuid());
					if(isRemark){
						terTree.setText(term.getName()+"<span typeId=\""+term.getHdType().getId()+"\" style=\"color:blue\">【"+term.getHdType().getName()+"】</span>");
					}else{
						terTree.setText(term.getName() == null ? "终端"+(i+1) : term.getName());
					}
					treeNodes.add(terTree);
				}
			}
			
			return treeNodes;
		}
	}
	
	public void findRegions()
	{
		List<Regions> regions = regionsService.findAll();
		JSONArray result=new JSONArray();
		for (Regions regions2 : regions) {
			result.add(buildCombo(regions2.getId().toString(),regions2.getName()));
		}
		writeToResponse(result.toString());
	}
	/**
	 * 根据ID查找区域
	 */
	public void findRegionsById()
	{
		String regions_id = request.getParameter("regionsId");
		if(StringUtils.isBlank(regions_id)) return;
		Regions reg = regionsService.findById(Long.valueOf(regions_id.replace("re_", "")));
		writeToResponse(JSONObject.fromObject(reg).toString());
	}
	
	public void findOrganizations()
	{
		String regionsId = request.getParameter("regionsId");
		List<Organization> orgs = null;
		JSONArray result=new JSONArray();
		if(StringUtils.isBlank(regionsId)){
			orgs = organizationService.findAll();
		}else{
			orgs = organizationService.findByRegions(Long.valueOf(regionsId));
		}
		for (Organization organization : orgs) {
			result.add(buildCombo(organization.getId().toString(),organization.getName()));
		}
		writeToResponse(result.toString());
	}
	
	public void findOrganizationById()
	{
		String organization_id = request.getParameter("organizationId");
		if(StringUtils.isBlank(organization_id)) return;
		Organization org = organizationService.findById(Long.valueOf(organization_id.replace("or_", "")));
		writeToResponse(JSONObject.fromObject(org).toString());
	}
	
	public void findDevices()
	{
		String organizationId = request.getParameter("organizationId");
		List<Device> devices = null;
		JSONArray result=new JSONArray();
		if(StringUtils.isBlank(organizationId)){
			devices = deviceService.findAll();
		}else{
			devices = deviceService.findByOrganization(Long.valueOf(organizationId));
		}
		for (Device device : devices) {
			result.add(buildCombo(device.getGuid().toString(),device.getName()));
		}
		writeToResponse(result.toString());
	}
	
	public void findDeviceById()
	{
		String device_id = request.getParameter("deviceId");
		if(StringUtils.isBlank(device_id)) return;
		Device org = deviceService.findById(device_id.replace("de_", "")); 
		writeToResponse(JSONObject.fromObject(org).toString());
	}
	
	public void findTerminalById()
	{
		String terminal_id = request.getParameter("terminalId");
		if(StringUtils.isBlank(terminal_id)) return;
		Terminal te = terminalService.findById(terminal_id.replace("te_", ""));  
		writeToResponse(JSONObject.fromObject(te).toString());
	}
	
	/**
	 * 封装combo数据
	 * @param id
	 * @param name
	 * @return
	 */
	private JSONObject buildCombo(String id,String name){
	        JSONObject result=new JSONObject();
	        result.put("value", id);
	        result.put("text", name);
	        return result;
	}
	
	public void saveRegions()
	{
		String parentId = request.getParameter("reParentId");
		String id = request.getParameter("regionsId");
		Regions reg = null;
		if(StringUtils.isBlank(id)){
			reg = new Regions();
			reg.setParentId(Long.valueOf(parentId.replace("re_", "")));
		}else{
			reg = regionsService.findById(Long.valueOf(id.replace("re_", "")));
		}
		reg.setAbbreviation(re.getAbbreviation());
		reg.setEnable(re.getEnable());
		reg.setName(re.getName());
		reg.setOrderNo(re.getOrderNo());
		reg.setPinYin(re.getPinYin());
		try{
			regionsService.saveOrUpdate(reg);
			writeToResponse("1");
		}catch (Exception e) {
			writeToResponse("0");
			e.printStackTrace();
		}
	}
	/**
	 * 保存区域
	 */
	public void deleteRegions()
	{
		String regionsId = request.getParameter("regionsId");
		if(StringUtils.isBlank(regionsId)){
			writeToResponse("0");
		}else{
			try{
				regionsService.delete(Long.valueOf(regionsId.replace("re_", "")));
				writeToResponse("1");
			}catch (Exception e) {
				writeToResponse("0");
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 保存组织
	 */
	public void saveOrganization()
	{
		String regionsId = request.getParameter("regionsId_or");
		String parentOrgId = request.getParameter("orParentId");
		String organizationId = request.getParameter("organizationId");
		Organization org = null;
		if(StringUtils.isNotBlank(regionsId)){//区域下面新增组织，父组织为0
			org = new Organization();
			org.set_parentId(0L);
			org.setRegions(regionsService.findById(Long.valueOf(regionsId.replace("re_", ""))));
		}else if(StringUtils.isBlank(organizationId) || StringUtils.isNotBlank(parentOrgId)){ //新增，且有上级组织
			String paId = parentOrgId.replace("or_", "");
			Organization orgParent = organizationService.findById(Long.valueOf(paId));
			org = new Organization();
			org.set_parentId(Long.valueOf(paId));
			org.setRegions(orgParent.getRegions());
		}else if(StringUtils.isNotBlank(organizationId)){ //修改
			org = organizationService.findById(Long.valueOf(organizationId.replace("or_", "")));
		}
		org.setEnable(orgni.getEnable());
		org.setName(orgni.getName());
		org.setType(orgni.getType());
		org.setSchoolId(orgni.getSchoolId());
		try{
			organizationService.saveOrUpdate(org);
			writeToResponse("1");
		}catch(Exception e){
			e.printStackTrace();
			writeToResponse("0");
		}
	}
	
	public void deleteOrganization()
	{
		String organizationId = request.getParameter("organizationId");
		if(StringUtils.isBlank(organizationId)){
			writeToResponse("0");
		}else{
			try{
				organizationService.delete(Long.valueOf(organizationId.replace("or_", "")));
				writeToResponse("1");
			}catch (Exception e) {
				writeToResponse("0");
				e.printStackTrace();
			}
		}
		
	}
	
	public void findHdType()
	{
	    List<HdType> type = hdTypeService.queryTypeAll();
	    JSONArray result=new JSONArray();
	    for (HdType hdType : type) {
            result.add(buildCombo(hdType.getId().toString(), hdType.getName()));
		}
	    writeToResponse(result.toString());
	}
	
	public void findParams()
	{
		List<Params> params = paramsService.findAll();
		JSONArray result=new JSONArray();
	    for (Params param : params) {
            result.add(buildCombo(param.getId().toString(), param.getName()));
		}
	    writeToResponse(result.toString());
	}
	
	public void saveDevice()
	{
		String organizationId = request.getParameter("de_organizationId");
		String parentDeviceId = request.getParameter("parentDeviceId");
		String deviceId = request.getParameter("deviceId");
		
		String hdTypeId = request.getParameter("hdTypeId");
		String paramsId = request.getParameter("paramsId");		
		Device device = null;
		if(StringUtils.isNotBlank(deviceId)){
			device = deviceService.findById(deviceId);
		}
		if(StringUtils.isNotBlank(organizationId)){ //从组织新增设备
			device.setOrganization(organizationService.findById(Long.valueOf(organizationId.replace("or_", ""))));
		}else if(StringUtils.isNotBlank(parentDeviceId)){ //从设备新增子设备
			device.setParentDeviceGuid(parentDeviceId.replace("de_", ""));
			device.setOrganization(deviceService.findById(parentDeviceId.replace("de_", "")).getOrganization());
		}
		device.setDomain(de.getDomain());
		device.setHdType(hdTypeService.queryTypeById(Long.valueOf(hdTypeId)));
		device.setMaintainStatus(de.getMaintainStatus());
		device.setName(de.getName());
		device.setParams(paramsService.findById(Long.valueOf(paramsId)));
		device.setRooter(de.getRooter());
		try{
			deviceService.saveOrUpdate(device);
			writeToResponse("1");
		}catch (Exception e) {
			e.printStackTrace();
			writeToResponse("0");
		}
	}
	
	public void deleteDevice()
	{
		String deviceGuid = request.getParameter("guid");
		if(StringUtils.isBlank(deviceGuid)){
			writeToResponse("0");
		}else{
			try{
				deviceService.delete(deviceGuid.replace("de_", ""));
				writeToResponse("1"); 
			}catch (Exception e) {
				writeToResponse("0");
				e.printStackTrace();
			}
		}
	}
	
	public void saveTerminal(){
		String terminalId = request.getParameter("terminalId");
		String te_deviceId = request.getParameter("te_deviceId");
		
		String hdTypeId = request.getParameter("hdTypeId_1");
		String paramsId = request.getParameter("paramsId_1");		
		Terminal terminal = null;
		RandomGUID myGUID = new RandomGUID();
		if(StringUtils.isNotBlank(te_deviceId)){ //新增终端，必须从设备上面点击新增
			terminal = new Terminal();
			terminal.setGuid(myGUID.valueAfterMD5);
			terminal.setDevice(deviceService.findById(te_deviceId.replace("de_", "")));
		}else if(StringUtils.isNotBlank(terminalId)){ //修改
			terminal = terminalService.findById(terminalId.replace("te_", ""));
		}
		terminal.setChannelNo(te.getChannelNo());
		terminal.setDomain(te.getDomain());
		terminal.setHdType(hdTypeService.queryTypeById(Long.valueOf(hdTypeId)));
        terminal.setMaintainStatus(te.getMaintainStatus());
        terminal.setName(te.getName());
        terminal.setParams(paramsService.findById(Long.valueOf(paramsId)));
        try{
        	terminalService.saveOrUpdate(terminal);
        	writeToResponse("1");
        }catch (Exception e) {
			e.printStackTrace();
			writeToResponse("0");
		}
	}
	
	public void deleteTerminal()
	{
		String terminalguid = request.getParameter("terminalguid");
		if(StringUtils.isBlank(terminalguid)){
			writeToResponse("0");
		}else{
			try{
				terminalService.delete(terminalguid.replace("te_", ""));
				writeToResponse("1"); 
			}catch (Exception e) {
				writeToResponse("0");
				e.printStackTrace();
			}
		}
	}
	
	public void findNoInNetDevice(){
		try{
		String serial = request.getParameter("serial");
		
		String startStr = request.getParameter("start"); // grid传过来的当前数据条数
		String limitStr = request.getParameter("limit"); // 每页显示的数据数
		int start = Integer.parseInt(StringUtils.isNotBlank(startStr) ? startStr : "0");
		int limit = Integer.parseInt(StringUtils.isNotBlank(limitStr) ? limitStr : "10");
		List<Device> list = deviceService.findNoInNet(serial,start,Integer.MAX_VALUE);
		GridDataModel<Device> page = new GridDataModel<Device>();
		int total = list.size();
		page.setPage(start / limit + 1);
		page.setRows(list);
		page.setTotal(total);
		String jsonStr = JSONObject.fromObject(page).toString();
		writeToResponse(jsonStr);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void findSchoolData() throws IOException{
		String name = request.getParameter("schoolName");
		if(StringUtils.isNotEmpty(name)){
			name = URLDecoder.decode(name, "UTF-8");
		}
		SchoolData sd = new SchoolData();
		sd.setName(name);
		String startStr = request.getParameter("start"); // grid传过来的当前数据条数
		String limitStr = request.getParameter("limit"); // 每页显示的数据数
		int start = Integer.parseInt(StringUtils.isNotBlank(startStr) ? startStr : "0");
		int limit = Integer.parseInt(StringUtils.isNotBlank(limitStr) ? limitStr : "10");
		GridDataModel<SchoolData> page = organizationService.findSchoolPage(sd, start, limit);
		String jsonStr = JSONObject.fromObject(page).toString();
		writeToResponse(jsonStr);
	}
	
	public void setRegionsService(RegionsService regionsService) {
		this.regionsService = regionsService;
	}
	public void setOrganizationService(OrganizationService organizationService) {
		this.organizationService = organizationService;
	}
	public void setDeviceService(DeviceService deviceService) {
		this.deviceService = deviceService;
	}
	public void setTerminalService(TerminalService terminalService) {
		this.terminalService = terminalService;
	}
	public void setHdTypeService(HdTypeService hdTypeService) {
		this.hdTypeService = hdTypeService;
	}
	public void setParamsService(ParamsService paramsService) {
		this.paramsService = paramsService;
	}
	public void setLocationService(LocationService locationService) {
		this.locationService = locationService;
	}

	public Regions getRe() {
		return re;
	}
	public void setRe(Regions re) {
		this.re = re;
	}
	public Organization getOrgni() {
		return orgni;
	}
	public void setOrgni(Organization orgni) {
		this.orgni = orgni;
	}
	public Device getDe() {
		return de;
	}
	public void setDe(Device de) {
		this.de = de;
	}
	public Terminal getTe() {
		return te;
	}
	public void setTe(Terminal te) {
		this.te = te;
	}

}
